<?php


namespace app\lib\qiniu;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Config;
use LinCmsTp5\admin\model\LinFile;
use app\lib\exception\file\FileException;
class PictureUploader extends Qiniu
{

    public function upload(){
        $file = $this->file;
        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;

        $auth      = new Auth($this->accessKey, $this->secretKey);
        $token  = $auth->uploadToken($this->bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        try{
            $url = $this->domain.$ret['key'];
            return $url;
        }catch (FileException $e){
            return '';
        }

    }

    public function base64Upload($img){
        //文件夹日期
        $ymd = date("Ymd");
        //图片路径地址
        $basedir = 'uploads/base64/'.$ymd.'';
        $fullpath = $basedir;

        if(!is_dir($fullpath)){
            mkdir($fullpath,0777,true);
        }
        $types = array('jpg', 'gif', 'png', 'jpeg');
        $img = str_replace(array('_','-'), array('/','+'), $img);
        $b64img = substr($img, 0,100);

        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $b64img, $matches)) {

            $type = $matches[2];
            if (!in_array($type, $types)) {
                return array('status' => 1, 'info' => '图片格式不正确，只支持 jpg、gif、png、jpeg哦！', 'url' => '');
            }
            $img = str_replace($matches[1], '', $img);
            $img = base64_decode($img);
            $photo = md5(date('YmdHis') . rand(1000, 9999)) . '.' . $type;
            file_put_contents($fullpath .'/' .$photo, $img);

            // 上传到七牛后保存的文件名
            $key = $photo;
            $auth      = new Auth($this->accessKey, $this->secretKey);
            $token  = $auth->uploadToken($this->bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $fullpath .'/' .$photo);
            if(file_exists($fullpath .'/' .$photo)){
                unlink($fullpath .'/' .$photo);
            }
            try{
                $url = $this->domain.$ret['key'];
                return $url;
            }catch (FileException $e){
                return '';
            }
        }
    }

    public function getQiniuToken(){
        $auth      = new Auth($this->accessKey, $this->secretKey);
        $token  = $auth->uploadToken($this->bucket);
        return $token;
    }

    public function getDomain(){
        return $this->domain;
    }

}
